package cn.cyj.security.ValidateCode;

import cn.cyj.security.sms.SmsCode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 用于生成登录界面二维码
 */
@RestController
public class ValidateCodeController {

    public final static String SESSION_KEY_IMAGE_CODE = "SESSION_KEY_IMAGE_CODE";
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
    public final static String SESSION_KEY_SMS_CODE = "SESSION_KEY_SMS_CODE";

    /**
     * 生成短线验证码
     *
     * @param request
     * @param response
     * @param mobile
     * @throws IOException
     */
    @GetMapping("/code/sms")
    public void createSmsCode(HttpServletRequest request, HttpServletResponse response, String mobile) throws IOException {
        //SmsCode smsCode = createSMSCode();
        SmsCode smsCode = aliSMSCode(mobile);
        if (smsCode != null) {
            sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_SMS_CODE + mobile, smsCode);
            // 输出验证码到控制台代替短信发送服务
            System.out.println("您的登录验证码为：" + smsCode.getCode() + "，有效时间为60秒");
        }
    }

    /**
     * 生成六位数随机数有效期60秒,放到初始化后的短信验证码对象中
     *
     * @return
     */
    private SmsCode createSMSCode() {
        String code = RandomStringUtils.randomNumeric(6);
        return new SmsCode(code, 60);
    }

    private SmsCode aliSMSCode(String mobile) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hebei", "LTAISMfsIAGiTu7y", "jXa7ue7IncpdLon33S9XaOHg2kWXIy");
        IAcsClient client = new DefaultAcsClient(profile);
        String randomSixNumber = RandomStringUtils.randomNumeric(6);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setAction("SendSms");
        request.setVersion("2017-05-25");
        request.putQueryParameter("RegionId", "cn-hebei");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", "小麦博客");
        request.putQueryParameter("TemplateCode", "SMS_187756621");
        request.putQueryParameter("TemplateParam", "{'code' : '" + randomSixNumber + "'}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            String result = response.getData();
            System.out.println("调用短信创建api返回报文-->" + result);
            JSONObject jsonObject = JSON.parseObject(result);
            String code = jsonObject.getString("Code");
            if ("OK".equals(code.toString()))
                return new SmsCode(randomSixNumber, 60);
            return null;

        } catch (ClientException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * CurrentPage is mandatory for this action.
     *
     * @param mobile
     * @param bizId
     * @return
     */
    private String querySMScode(String mobile, String bizId) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hebei", "LTAISMfsIAGiTu7y", "jXa7ue7IncpdLon33S9XaOHg2kWXIy");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setAction("QuerySendDetails");
        request.setVersion("2017-05-25");
        request.putQueryParameter("RegionId", "cn-hebei");
        request.putQueryParameter("PageSize", "1");
        request.putQueryParameter("PhoneNumber", mobile);
        request.putQueryParameter("SendDate", "2017-05-25");
        request.putQueryParameter("BizId", bizId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            String result = response.getData();
            System.out.println("查询短信详细信息api返回报文-->" + result);
            JSONObject jsonObject = JSON.parseObject(result);
            String code = jsonObject.getString("Code");
            if ("OK".equals(code.toString())) {
                JSONArray smsSendDetailDTOs = jsonObject.getJSONArray("SmsSendDetailDTOs");
                if (smsSendDetailDTOs != null && smsSendDetailDTOs.size() > 0) {
                    JSONObject SmsSendDetailDTO = smsSendDetailDTOs.getJSONObject(0);
                    if (SmsSendDetailDTO != null) {
                        String outId = SmsSendDetailDTO.getString("OutId");
                        return outId;
                    }
                }
            }
            return null;

        } catch (ClientException e) {
            e.printStackTrace();
            return null;
        }
    }

    @GetMapping("/code/image")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageCode imageCode = createImageCode();
        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_IMAGE_CODE, imageCode);
        ImageIO.write(imageCode.getImage(), "jpg", response.getOutputStream());
    }

    private ImageCode createImageCode() {

        int width = 100; // 验证码图片宽度
        int height = 36; // 验证码图片长度
        int length = 4; // 验证码位数
        int expireIn = 60; // 验证码有效时间 60s

        //创建图片指定大小
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics g = bufferedImage.getGraphics();

        Random random = new Random();

        //给生成的文字设置字体赋予随机颜色
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
        g.setColor(getRandColor(160, 200));
        //字体所在位置偏移?
        for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }
        //没看懂
        StringBuilder sRand = new StringBuilder();
        for (int i = 0; i < length; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand.append(rand);
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(rand, 13 * i + 6, 16);
        }
        g.dispose();
        return new ImageCode(bufferedImage, sRand.toString(), expireIn);
    }

    /**
     * 随机生成颜色
     *
     * @param fc
     * @param bc
     * @return
     */
    private Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}
